﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using Flower.Directory.Management.Scripting;
using Flower.Directory.Scripting;
using Flower.Services;
using Jurassic;
using Setup = Flower.Directory.Management.Scripting.Setup;
using Flower.Logging;
using Flower.Services.Clients;
using System.Transactions;

namespace Flower.Directory.Management.Cmd
{
    public class Program
    {
        private static bool _run = true;

        public static void Main(string[] procArgs)
        {
            try
            {
                string[] scripts, args;

                ParseArgs(procArgs, out scripts, out args);

                ScriptEngine scriptEngine =
                    Setup.InitEngine
                    (
                        Directory.Scripting.Setup.CreateEngine()
                    );

                var argsArray =
                    scriptEngine
                        .Array
                        .Construct((object[])args);

                scriptEngine.SetGlobalValue("$args", argsArray);
                scriptEngine.SetGlobalValue("$dir", new DirectoryObject(scriptEngine, new WcfClientFactory<IDirectory>().Create("Directory")));
                scriptEngine.SetGlobalFunction("exit", new Action(() => { _run = false; }));

                if (scripts.Length == 0)
                {
                    RunInteractively(scriptEngine);
                }
                else
                {
                    foreach (string scriptPath in args)
                    {
                        try
                        {
                            TransactionHelper.Scope
                            (
                                IsolationLevel.ReadCommitted,
                                TimeSpan.FromHours(1), 
                                () => scriptEngine.ExecuteFile(scriptPath)
                            );
                        }
                        catch (Exception ex)
                        {
                            LogManager.Flush();

                            Console.Error.WriteLine("Error:");
                            Console.Error.WriteLine(ex.ToString());
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                Console.Error.WriteLine("Error:");
                Console.Error.WriteLine(ex.ToString());
            }
        }

        private static void ParseArgs(string[] procArgs, out string[] scripts, out string[] args)
        {
            var scriptsList = new List<string>();
            var argsList = new List<string>();

            var currentList = scriptsList;

            foreach (string arg in procArgs)
            {
                if (arg == "/")
                {
                    currentList = argsList;
                    continue;
                }

                currentList.Add(arg);
            }

            scripts = scriptsList.ToArray();
            args = argsList.ToArray();
        }

        private static void RunInteractively(ScriptEngine scriptEngine)
        {
            Console.CursorVisible = true;

            while (_run)
            {
                try
                {
                    Console.Write(scriptEngine.Evaluate<string>("$wd") + ">");

                    string line = Console.ReadLine();
                    object val = 
                        TransactionHelper.Scope
                        (
                            IsolationLevel.ReadCommitted,
                            TimeSpan.FromHours(1),
                            () => scriptEngine.Evaluate(line)
                        );

                    LogManager.Flush();

                    if (_run && val != null && !(val is Undefined))
                    {
                        Printer.Print(Console.Out, val, true);
                    }
                }
                catch (FaultException<DirectoryFault> ex)
                {
                    LogManager.Flush();

                    Console.Error.WriteLine("Error:");
                    Console.Error.WriteLine(ex.Message);
                }
                catch (IOException ex)
                {
                    LogManager.Flush();

                    Console.Error.WriteLine(ex.Message);
                }
                catch (JavaScriptException ex)
                {
                    LogManager.Flush();

                    Console.Error.WriteLine(ex.Message);
                }
                catch (Exception ex)
                {
                    LogManager.Flush();

                    Console.Error.WriteLine("Error:");
                    Console.Error.WriteLine(ex.ToString());
                }
            }
        }
    }
}
